import React, { useState } from 'react';
import { Card, Table, Button, Modal, Form, Input, Select, message } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined } from '@ant-design/icons';

const { Option } = Select;

// 模拟用户数据
const mockUsers = [
  { id: 1, name: '张三', email: 'zhangsan@example.com', role: '管理员', status: '启用' },
  { id: 2, name: '李四', email: 'lisi@example.com', role: '操作员', status: '启用' },
  { id: 3, name: '王五', email: 'wangwu@example.com', role: '查看者', status: '禁用' },
  { id: 4, name: '赵六', email: 'zhaoliu@example.com', role: '操作员', status: '启用' },
  { id: 5, name: '钱七', email: 'qianqi@example.com', role: '查看者', status: '启用' },
];

const Users = () => {
  const [users, setUsers] = useState(mockUsers);
  const [isAddModalOpen, setIsAddModalOpen] = useState(false);
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [currentUser, setCurrentUser] = useState(null);
  const [searchText, setSearchText] = useState('');
  const [form] = Form.useForm();

  const handleAdd = () => {
    setIsAddModalOpen(true);
    form.resetFields();
  };

  const handleEdit = (user) => {
    setCurrentUser(user);
    form.setFieldsValue(user);
    setIsEditModalOpen(true);
  };

  const handleDelete = (id) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除此用户吗？',
      onOk: () => {
        setUsers(users.filter(user => user.id !== id));
        message.success('删除成功');
      },
    });
  };

  const handleAddOk = () => {
    form.validateFields()
      .then(values => {
        const newUser = {
          id: users.length + 1,
          ...values,
        };
        setUsers([...users, newUser]);
        setIsAddModalOpen(false);
        message.success('添加成功');
      })
      .catch(err => {
        console.error('表单验证失败:', err);
      });
  };

  const handleEditOk = () => {
    form.validateFields()
      .then(values => {
        const updatedUsers = users.map(user =>
          user.id === currentUser.id ? { ...user, ...values } : user
        );
        setUsers(updatedUsers);
        setIsEditModalOpen(false);
        message.success('更新成功');
      })
      .catch(err => {
        console.error('表单验证失败:', err);
      });
  };

  const filteredUsers = users.filter(user =>
    user.name.includes(searchText) ||
    user.email.includes(searchText) ||
    user.role.includes(searchText)
  );

  const columns = [
    { title: 'ID', dataIndex: 'id', key: 'id' },
    { title: '姓名', dataIndex: 'name', key: 'name' },
    { title: '邮箱', dataIndex: 'email', key: 'email' },
    { title: '角色', dataIndex: 'role', key: 'role' },
    { title: '状态', dataIndex: 'status', key: 'status', render: status => (
      <span style={{ color: status === '启用' ? 'green' : 'red' }}>{status}</span>
    )},
    { title: '操作', key: 'action', render: (_, record) => (
      <div>
        <Button type="primary" icon={<EditOutlined />} size="small" onClick={() => handleEdit(record)} style={{ marginRight: 8 }}>编辑</Button>
        <Button type="danger" icon={<DeleteOutlined />} size="small" onClick={() => handleDelete(record.id)}>删除</Button>
      </div>
    )},
  ];

  return (
    <div>
      <Card title="用户管理" variant="filled" extra={<Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>添加用户</Button>}>
        <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'flex-end' }}>
          <Input
            placeholder="搜索用户..."
            prefix={<SearchOutlined />}
            value={searchText}
            onChange={e => setSearchText(e.target.value)}
            style={{ width: 300 }}
          />
        </div>
        <Table columns={columns} dataSource={filteredUsers} rowKey="id" />
      </Card>

      {/* 添加用户模态框 */}
      <Modal
        title="添加用户"
        open={isAddModalOpen}
        onOk={handleAddOk}
        onCancel={() => setIsAddModalOpen(false)}
      >
        <Form form={form} layout="vertical">
          <Form.Item name="name" label="姓名" rules={[{ required: true, message: '请输入姓名' }]}>
            <Input placeholder="请输入姓名" />
          </Form.Item>
          <Form.Item name="email" label="邮箱" rules={[{ required: true, message: '请输入邮箱' }, { type: 'email', message: '请输入有效的邮箱地址' }]}>
            <Input placeholder="请输入邮箱" />
          </Form.Item>
          <Form.Item name="role" label="角色" rules={[{ required: true, message: '请选择角色' }]}>
            <Select placeholder="请选择角色">
              <Option value="管理员">管理员</Option>
              <Option value="操作员">操作员</Option>
              <Option value="查看者">查看者</Option>
            </Select>
          </Form.Item>
          <Form.Item name="status" label="状态" rules={[{ required: true, message: '请选择状态' }]}>
            <Select placeholder="请选择状态">
              <Option value="启用">启用</Option>
              <Option value="禁用">禁用</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>

      {/* 编辑用户模态框 */}
      <Modal
        title="编辑用户"
        open={isEditModalOpen}
        onOk={handleEditOk}
        onCancel={() => setIsEditModalOpen(false)}
      >
        <Form form={form} layout="vertical">
          <Form.Item name="name" label="姓名" rules={[{ required: true, message: '请输入姓名' }]}>
            <Input placeholder="请输入姓名" />
          </Form.Item>
          <Form.Item name="email" label="邮箱" rules={[{ required: true, message: '请输入邮箱' }, { type: 'email', message: '请输入有效的邮箱地址' }]}>
            <Input placeholder="请输入邮箱" />
          </Form.Item>
          <Form.Item name="role" label="角色" rules={[{ required: true, message: '请选择角色' }]}>
            <Select placeholder="请选择角色">
              <Option value="管理员">管理员</Option>
              <Option value="操作员">操作员</Option>
              <Option value="查看者">查看者</Option>
            </Select>
          </Form.Item>
          <Form.Item name="status" label="状态" rules={[{ required: true, message: '请选择状态' }]}>
            <Select placeholder="请选择状态">
              <Option value="启用">启用</Option>
              <Option value="禁用">禁用</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Users;